<template>
  <div class="article-card" @click="viewArticle">
    <!-- 文章主体 -->
    <div class="card-content">
      <!-- 文章头部信息 -->
      <div class="card-header">
      <div class="author-info">
        <el-avatar 
          :size="40" 
          :src="article.authorAvatar ? getAvatarUrl(article.authorAvatar) : defaultAvatar" 
          @click.stop="viewAuthor"
        />
          <div class="author-details">
            <div class="author-name" @click.stop="viewAuthor">{{ article.authorName }}</div>
            <div class="post-time">{{ formatTime(article.createTime) }}</div>
          </div>
        </div>
        
        <div class="card-tags">
          <el-tag 
            v-if="article.boardName" 
            size="small" 
            type="primary" 
            effect="plain"
            class="board-tag"
            @click.stop="navigateToBoard"
          >
            {{ article.boardName }}
          </el-tag>
          
          <el-tag 
            v-for="tag in parsedTags" 
            :key="tag" 
            size="small" 
            class="article-tag"
            @click.stop="navigateToTag(tag)"
          >
            {{ tag }}
          </el-tag>
      </div>
      </div>
      
      <!-- 文章标题与预览 -->
      <div class="card-body">
        <h3 class="article-title">{{ article.title }}</h3>
        <div class="article-preview" v-html="formatContent"></div>
      </div>
      
      <!-- 文章缩略图 -->
      <div v-if="article.coverImage" class="article-cover">
        <img :src="article.coverImage" alt="Cover Image" />
      </div>
      
      <!-- 文章底部互动区域 -->
      <div class="card-footer">
        <div class="stats">
          <div class="stat-item">
            <el-icon><View /></el-icon>
            <span>{{ formatNumber(article.viewCount || 0) }}</span>
          </div>
          <div class="stat-item">
            <el-icon><ChatLineRound /></el-icon>
            <span>{{ formatNumber(article.commentCount || 0) }}</span>
      </div>
    </div>
    
        <div class="actions">
          <el-button 
            type="primary" 
            :icon="article.isLiked ? 'Star' : 'StarFilled'" 
            circle 
            plain
            :class="{ 'is-liked': article.isLiked }"
            @click.stop="likeArticle"
          ></el-button>
          <el-button 
            type="info" 
            icon="Share" 
            circle 
            plain
            @click.stop="shareArticle"
          ></el-button>
          <el-dropdown 
            trigger="click" 
            @command="handleCommand" 
            @click.stop
          >
            <el-button 
              type="info" 
              icon="More" 
              circle 
              plain
            ></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="save"><el-icon><Collection /></el-icon> 收藏文章</el-dropdown-item>
                <el-dropdown-item v-if="isArticleAuthor" command="edit"><el-icon><Edit /></el-icon> 编辑文章</el-dropdown-item>
                <el-dropdown-item v-if="isArticleAuthor || isAdmin" command="delete"><el-icon><Delete /></el-icon> 删除文章</el-dropdown-item>
                <el-dropdown-item command="report"><el-icon><Warning /></el-icon> 举报</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import config from '@/config'

export default {
  name: 'ArticleCard',
  
  props: {
    article: {
      type: Object,
      required: true
    }
  },
  
  emits: ['view', 'like'],
  
  setup(props, { emit }) {
    const store = useStore()
    const router = useRouter()
    const defaultAvatar = require('@/assets/default-avatar.png')
    
    // 使用config处理头像URL
    const getAvatarUrl = (url) => {
      console.log('ArticleCard 原始头像URL:', url);
      const result = config.getDirectAvatarUrl(url);
      console.log('ArticleCard 处理后头像URL:', result);
      return result;
    }
    
    // 本地状态，用于跟踪UI状态变化
    const localArticleState = computed(() => ({
      isLiked: props.article.isLiked,
      likeCount: props.article.likeCount || 0
    }))
    
    // 计算属性
    const userId = computed(() => store.getters.userId || null)
    const isAdmin = computed(() => store.getters.isAdmin)
    const isArticleAuthor = computed(() => props.article.authorId === userId.value)
    
    const parsedTags = computed(() => {
      if (!props.article.tags) return []
      return typeof props.article.tags === 'string' 
        ? props.article.tags.split(',').filter(tag => tag.trim()) 
        : props.article.tags
    })
    
    const formatContent = computed(() => {
      if (!props.article.content) return ''
      // 提取纯文本内容并截断
      const textContent = props.article.content
        .replace(/<[^>]+>/g, '')  // 移除HTML标签
        .replace(/&[^;]+;/g, '')  // 移除HTML实体
        .trim()
      
      return textContent.length > 150
        ? textContent.substring(0, 150) + '...'
        : textContent
    })
    
    // 方法
    const formatTime = (timestamp) => {
      if (!timestamp) return ''
      
      const date = dayjs(timestamp)
      const now = dayjs()
      const diffDays = now.diff(date, 'day')
      
      if (diffDays < 1) {
        return date.fromNow() // 今天内显示"几小时前"
      } else if (diffDays < 7) {
        return date.format('dddd HH:mm') // 一周内显示"星期几 时:分"
      } else if (date.year() === now.year()) {
        return date.format('MM-DD HH:mm') // 今年内显示"月-日 时:分"
      } else {
        return date.format('YYYY-MM-DD') // 跨年显示完整日期
      }
    }
    
    const formatNumber = (num) => {
      if (num < 1000) return num
      if (num < 10000) return (num / 1000).toFixed(1) + 'K'
      return (num / 10000).toFixed(1) + 'W'
    }
    
    const viewArticle = () => {
      emit('view', props.article.id)
      router.push(`/article/${props.article.id}`)
    }
    
    const viewAuthor = () => {
      router.push(`/user/${props.article.authorId}`)
      }
    
    const navigateToBoard = () => {
      if (props.article.boardId) {
        router.push(`/board/${props.article.boardId}`)
      }
    }
    
    const navigateToTag = (tag) => {
      router.push({
        path: '/articles',
        query: { tag }
      })
    }
    
    const likeArticle = async () => {
      try {
        if (!store.getters['user/isLoggedIn']) {
          ElMessage.warning('请先登录后再点赞')
          router.push('/login')
          return
        }
        
        emit('like', props.article.id)
        
        // 当前点赞状态取反
        const isLiked = !props.article.isLiked
        
        // 调用Vuex action
        const success = await store.dispatch('article/toggleLike', {
          articleId: props.article.id,
          isLike: isLiked
        })
        
        if (success) {
          // 更新本地状态
          props.article.isLiked = isLiked
          props.article.likeCount = isLiked
            ? (props.article.likeCount || 0) + 1
            : Math.max((props.article.likeCount || 1) - 1, 0)
          
          ElMessage.success(isLiked ? '点赞成功' : '已取消点赞')
        } else {
          ElMessage.error('操作失败，请稍后重试')
        }
      } catch (error) {
        console.error('点赞失败:', error)
        ElMessage.error('操作失败，请稍后重试')
      }
    }
    
    const shareArticle = () => {
      try {
        // 复制链接到剪贴板
        const url = `${window.location.origin}/article/${props.article.id}`
        navigator.clipboard.writeText(url)
        ElMessage.success('链接已复制到剪贴板')
      } catch (error) {
        console.error('分享失败:', error)
        ElMessage.error('分享失败，请手动复制链接')
      }
    }
    
    const handleCommand = async (command) => {
      switch (command) {
        case 'save':
          ElMessage.success('文章已收藏')
          break
        case 'edit':
          router.push(`/edit/${props.article.id}`)
          break
        case 'delete':
          ElMessageBox.confirm('确定要删除这篇文章吗？此操作不可恢复。', '删除确认', {
            confirmButtonText: '确定删除',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(async () => {
            try {
              await store.dispatch('article/deleteArticle', props.article.id)
              ElMessage.success('文章已删除')
            } catch (error) {
              console.error('删除失败:', error)
              ElMessage.error('删除失败，请稍后重试')
            }
          }).catch(() => {})
          break
        case 'report':
          ElMessage.info('举报已提交，我们会尽快处理')
          break
      }
    }
    
    return {
      defaultAvatar,
      parsedTags,
      formatContent,
      isArticleAuthor,
      isAdmin,
      formatTime,
      formatNumber,
      viewArticle,
      viewAuthor,
      navigateToBoard,
      navigateToTag,
      likeArticle,
      shareArticle,
      handleCommand,
      localArticleState,
      getAvatarUrl
    }
  }
}
</script>

<style scoped>
.article-card {
  background-color: var(--bg-primary);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  transition: all var(--transition-normal);
  margin-bottom: var(--space-5);
  overflow: hidden;
  cursor: pointer;
}

.article-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
  }
  
.card-content {
  padding: var(--space-5);
}

/* Card Header */
.card-header {
    display: flex;
    justify-content: space-between;
  margin-bottom: var(--space-4);
  flex-wrap: wrap;
  gap: var(--space-2);
}
    
    .author-info {
      display: flex;
      align-items: center;
      }
      
.author-details {
  margin-left: var(--space-3);
}
        
        .author-name {
  font-weight: var(--font-medium);
  color: var(--text-primary);
  margin-bottom: var(--space-1);
          cursor: pointer;
  transition: color var(--transition-fast);
}
          
.author-name:hover {
  color: var(--primary-color);
          }

.post-time {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
        }
        
.card-tags {
          display: flex;
  flex-wrap: wrap;
  gap: var(--space-2);
          align-items: center;
}

.board-tag {
            cursor: pointer;
}

.article-tag {
  cursor: pointer;
  background-color: var(--gray-100);
  border-color: var(--gray-300);
  color: var(--text-secondary);
            }

/* Card Body */
.card-body {
  margin-bottom: var(--space-4);
      }
    
    .article-title {
  font-size: var(--text-xl);
  font-weight: var(--font-bold);
  margin-bottom: var(--space-3);
  color: var(--text-primary);
  line-height: 1.4;
  transition: color var(--transition-fast);
}

.article-card:hover .article-title {
  color: var(--primary-color);
    }
    
.article-preview {
  color: var(--text-secondary);
      line-height: 1.6;
  margin-bottom: var(--space-3);
  font-size: var(--text-base);
  overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }
    
/* Article Cover */
    .article-cover {
  margin: var(--space-3) 0;
  border-radius: var(--radius-md);
      overflow: hidden;
  max-height: 200px;
}
      
.article-cover img {
        width: 100%;
        height: 100%;
  object-fit: cover;
  transition: transform var(--transition-normal);
      }

.article-card:hover .article-cover img {
  transform: scale(1.05);
    }
    
/* Card Footer */
.card-footer {
      display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: var(--space-4);
  padding-top: var(--space-3);
  border-top: 1px solid var(--gray-200);
      }

.stats {
  display: flex;
  gap: var(--space-4);
}

.stat-item {
      display: flex;
      align-items: center;
  color: var(--text-tertiary);
  font-size: var(--text-sm);
}
      
.stat-item .el-icon {
  margin-right: var(--space-1);
}

.actions {
  display: flex;
  gap: var(--space-2);
}

.actions .el-button {
  transition: all var(--transition-fast);
}

.actions .el-button:hover {
  transform: scale(1.1);
          }
          
.is-liked {
  color: var(--danger-color);
  border-color: var(--danger-color);
          }

/* 响应式调整 */
@media (max-width: 768px) {
  .card-content {
    padding: var(--space-4);
  }
  
  .card-header {
    flex-direction: column;
    gap: var(--space-3);
  }
  
  .author-info {
    width: 100%;
  }
  
  .card-tags {
    width: 100%;
    justify-content: flex-start;
  }
  
  .card-footer {
    flex-wrap: wrap;
    gap: var(--space-3);
  }
  
  .stats, .actions {
    width: 100%;
    justify-content: space-between;
      }
    }
</style>